package com.gridmobi.xrtb.handler.impl;

import com.gridmobi.xrtb.common.IPUtil;
import com.gridmobi.xrtb.handler.Mailer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author huangyongchao
 */
@Service
public class SysError {

    @Autowired
    private Mailer mailer;
    public static AtomicInteger REDIS_ERROR_TIMES = new AtomicInteger(0);
    public static AtomicInteger DATA_SYNCH_ERROR_TIMES = new AtomicInteger(0);
    public static AtomicInteger KAFKA_ERROR_TIMES = new AtomicInteger(0);

    @Value("${errortimes.redis}")
    private int rediserrortimes = 5;
    @Value("${errortimes.datasynch}")
    private float datasyncherrortimes = 10;

    @Value("${errortimes.datasynch}")
    private float kafkaerrortimes = 100;

    @Value("${rtbname}")
    private String  rtbname;

    public boolean noBidByRedisError() {
        return REDIS_ERROR_TIMES.get() >= rediserrortimes;
    }

    public boolean noBidByDataSynchError() {
        return DATA_SYNCH_ERROR_TIMES.get() >= datasyncherrortimes;
    }

    public boolean noBidByKafkaError() {
        return KAFKA_ERROR_TIMES.get() >= kafkaerrortimes;
    }

    public void redisError(Throwable e) {
        int errors = REDIS_ERROR_TIMES.incrementAndGet();
        if (errors > rediserrortimes) {
            mailer.sendErrorMail("RTB REDIS ERROR:"+rtbname, IPUtil.getHost()+trackStr(e));
        }

    }

    public void datasynchError(Throwable e) {
        int errors = DATA_SYNCH_ERROR_TIMES.incrementAndGet();
        if (errors > datasyncherrortimes) {
            mailer.sendErrorMail("RTB DATA SYNCH ERROR:"+rtbname, IPUtil.getHost()+trackStr(e));
        }

    }


    public void kafkaError(Throwable e) {
        int errors = KAFKA_ERROR_TIMES.incrementAndGet();
        if (errors > kafkaerrortimes) {
            mailer.sendErrorMail("RTB KAFKA ERROR:"+rtbname, IPUtil.getHost()+trackStr(e));
        }

    }


    private String trackStr(Throwable e) {
        StringBuilder stringBuilder = new StringBuilder(e.getMessage());
        for (StackTraceElement track : e.getStackTrace()) {
            stringBuilder.append(track.toString());
        }
        return stringBuilder.toString();
    }
    @PostConstruct
    public void init(){
        System.out.println("++++++++"+rtbname+"++++++++");
    }
}
